package conf

import (
	"bytes"
	_ "embed"
	"flag"
	"fmt"
	gorm_v2 "gitee.com/youbeiwuhuan/go-xxljob/pkg/gormv2"
	"gitee.com/youbeiwuhuan/go-xxljob/pkg/zaps"
	"github.com/spf13/viper"
	"io"
	"os"
)

type Server struct {
	Port int `mapstructure:"port"`
}

type AppConfig struct {
	Zap   zaps.ZapConfig      `mapstructure:"zap"`
	Gorm2 gorm_v2.Gorm2Config `mapstructure:"gormv2"`
}

//go:embed config.yaml
var Cfg []byte

func GetConfFile() io.Reader {
	var filePath string
	// -config=./config.yml
	flag.StringVar(&filePath, "config", "", "配置文件路径")
	//解析命令行参数
	flag.Parse()
	fmt.Println(filePath)
	if "" == filePath {
		return bytes.NewReader(Cfg)
	}

	// 打开文件，准备读取
	file, err := os.Open("example.txt")
	if err != nil {
		fmt.Println("Error opening file:", err)
	}
	defer file.Close() // 确保在函数返回时关闭文件
	return file
}

func Load(file io.Reader) AppConfig {
	config := viper.New()
	//开始读取环境变量，如果没有调用这个函数，则下面无法读取到path的值
	config.AutomaticEnv()
	config.SetConfigType("yaml")
	config.ReadConfig(file)

	// 配置读到结构体
	var cfg AppConfig
	if err := config.Unmarshal(&cfg); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	} else {
		fmt.Println(cfg)
	}

	return cfg
}
